<?php
/**
 * Created by PhpStorm.
 * User: 雨寒
 * Date: 2018/12/19
 * Time: 下午3:21
 */

namespace app\admin\controller;

use think\Db;
use app\common\model\Order as commonorder;
use app\common\model\Message;

class Order extends Common
{

    //订单列表
    public function cancel()
    {
        $this->templateTitle("取消订单列表");
        $order = \db("order_cancel")->alias("or")->join("user buy", "or.buyuid=buy.id", "left")->join("user match", "match.id=or.peiduiuid", "left");
        $param = input("get.");
        if(isset($param["id"]) && $param["id"] != ""){
            $order->where("or.id", $param["id"]);
        }

        if(isset($param["userinfo"]) && $param["userinfo"] != ""){
            $order->where("buy.username|buy.selfphone", $param["userinfo"]);
        }

        if(isset($param["time_range"]) && $param["time_range"] != ""){
            list($start_time, $end_time) = explode("~", $param["time_range"]);
        }else{
            $start_time =  date("Y-m-d", strtotime("-7 day"));
            $end_time = date("Y-m-d");
        }
        $order->where("or.ctime", ">", strtotime($start_time));
        $order->where("or.ctime", "<", strtotime($end_time)+86400);
        $this->assign("range_start", ["time_range" => $start_time]);
        $this->assign("range_end", ["time_range" => $end_time]);

        if(isset($param["peiduistatus"]) && $param["peiduistatus"] != ""){
            $order->where("or.peiduistatus", $param["peiduistatus"]);
        }

        if(isset($param["peiduiuid"]) && $param["peiduiuid"] != ""){
            $order->where("match.username|match.selfphone", $param["peiduiuid"]);
        }

        //获取订单列表
        $list = $order->field("or.*, buy.username b_username, buy.selfphone b_selfphone, match.username m_username, match.selfphone m_selfphone")
            ->order("or.id DESC")
            ->paginate(10);
        $this->assign("list", $list);
        $this->assign("param", $param);

        return $this->fetch('order/cancel');
    }

    //订单列表
    public function index(){
        $this->templateTitle("订单列表");
        $order = \db(config("db_order_table"))->alias("or")->join("user buy", "or.buyuid=buy.id", "left")->join("user match", "match.id=or.peiduiuid", "left");
        $param = input("get.");
        if(isset($param["id"]) && $param["id"] != ""){
            $order->where("or.id", $param["id"]);
        }

        if(isset($param["userinfo"]) && $param["userinfo"] != ""){
            $order->where("buy.username|buy.selfphone", $param["userinfo"]);
        }

        if(isset($param["time_range"]) && $param["time_range"] != ""){
            list($start_time, $end_time) = explode("~", $param["time_range"]);
        }else{
            $start_time =  date("Y-m-d", strtotime("-7 day"));
            $end_time = date("Y-m-d");
        }
        $order->where("or.ctime", ">", strtotime($start_time));
        $order->where("or.ctime", "<", strtotime($end_time)+86400);
        $this->assign("range_start", ["time_range" => $start_time]);
        $this->assign("range_end", ["time_range" => $end_time]);

        if(isset($param["paystatus"]) && $param["paystatus"] != ""){
            $order->where("or.paystatus", $param["paystatus"]);
        }

        if(isset($param["zhiding"]) && $param["zhiding"] != ""){
            if($param['zhiding']==1){
              $order->where("or.applyid",'=',0);
            }
            if($param['zhiding']==2){
              $order->where("or.applyid",'>',0);
            }

        }

        if(isset($param["peiduistatus"]) && $param["peiduistatus"] != ""){
            $order->where("or.peiduistatus", $param["peiduistatus"]);
        }

        if(isset($param["peiduiuid"]) && $param["peiduiuid"] != ""){
            $order->where("match.username|match.selfphone", $param["peiduiuid"]);
        }

        //拉取所有商品
        $good_id = input("good_id", 0);
        if (!empty($good_id)) {
            $order->where("or.productid", $good_id);
        }
        $this->assign("good_id", $good_id);
        $good_list = db("goods")->field("id, title")->select();
        $this->assign("good_list", $good_list);


        //获取订单列表
        $list = $order->field("or.*, buy.username b_username, buy.selfphone b_selfphone, match.username m_username, match.selfphone m_selfphone")
            ->order("or.id DESC")
            ->paginate(10);
        $this->assign("list", $list);
        $this->assign("param", $param);

        $bar['buyall']  = \db(config('db_order_table'))->sum('price');
        $bar['buyok']   = \db(config('db_order_table'))->where('peiduistatus=2 and paystatus=2')->sum('price');
        $bar['buying']  = ($bar['buyall']-$bar['buyok']);

        $this->assign("all_money", $bar);
        return $this->fetch('order/index');
    }

    /*订单详情*/
    public function orderInfo()
    {
        $orderid = input('id');
        /*订单基本信息*/
        $order = \db(config("db_order_table"))->alias("or")->join("user buy", "or.buyuid=buy.id")->join("user match", "match.id=or.peiduiuid", "left")->where('or.id', $orderid)->field("or.*, buy.username b_username, buy.selfphone b_selfphone, match.username m_username, match.selfphone m_selfphone")->find();
        /*订单收益详情*/
        $orderearns = \db("orderearn")->where('orderid', $orderid)->order("ctime desc")->select();
        $this->layoutModal();
        $this->assign('orderinfo', $order);
        $this->assign('orderearns', $orderearns);
        $this->assign("range_start2", ["ctime"=>date("Y-m-d H:i:s", $order["ctime"])]);
		/*订单SCB详情*/
		$botlist = \db("orderbot")->where('orderid','=',$orderid)->order("ctime desc")->select();
		if(!empty($botlist)){
		    foreach($botlist as $k => $v) {
				$botlist[$k]['goodname'] = db("goods")->where("id='".$v['proid']."'")->value('title');
		    }
	    }
		$this->assign('botlist', $botlist);

        return $this->fetch("order_info");
    }

    /*修改下单时间让这个订单可以提前卖出去*/
    public function changeCtime(){
        $id = intval(input("id"));
        if(empty($id)){
            $this->error('找不到此订单信息，无法添加备注！');exit;
        }
        $info = \db(config("db_order_table"))->where("id='".$id."'")->find();
        if(empty($info)){
            $this->error('找不到此订单信息，无法添加备注！');exit;
        }
        $postdate = trim($_POST['ctime']);
        $data['ctime'] = strtotime($postdate);
        $cansaletime  =  ($data['ctime']+86400*$info['daynum']);
        $cansaletimedate = date('Y-m-d',$cansaletime);
        $data['cansaletime'] = strtotime($cansaletimedate);
        $s = \db(config("db_order_table"))->where("id='".$id."'")->update($data);
        if($s){
            $this->ajaxSuccess('设置成功！');
        }else{
            $this->ajaxError('设置失败');
        }
    }

    /**
     * 订单拆分
     */
    public function orderExplode(){
        if(request()->isGet()){
            $this->layoutModal();
            $order = \db(config("db_order_table"))->where("id", input("id"))->find();
            $this->assign("order", $order);
            return $this->fetch("order_explode");
        }
        $price = trim($_POST['price']);
        $price_ary = explode(',',$price);
        $price_all = 0;
        $price_newary = [];
        foreach($price_ary as $k=>$v){
            if(!empty($v) && $v>0){
                $price_all = ($price_all+$v);//总金额
                $price_newary[] = $v;        //新数组
            }
        }
        //根据id去查询这个订单当前价格是多少
        $id = intval($_POST['order_id']);
        $info = \db(config('db_order_table'))->where("id='".$id."'")->find();
        if(empty($id) || empty($info)){
            $this->ajaxError("订单不存在");
        }
        $cha_price_first = intval($info['price']);
        $cha_price_secod = intval($price_all);
        if($cha_price_first!=$cha_price_secod){
            $this->ajaxError("拆分金额和本次消费金额不一样，请检查！");
        }
        //开始写拆分算法,主要是拆分atc和所用的财分
        $good = [];
        foreach ($price_newary as $k1=>$v1){
            //获取价格区间内商品信息
            $g = \db("goods")->where("price1", "<", $v1)->where("price2", ">=", $v1)->where("isshow", 1)->where("isclose", 1)->find();
            if(empty($g)){
                $this->ajaxError("拆分金额".$v1."暂时无此商品销售");
            }
            $good[$k1] = $g;
        }
        $z = 0;
        foreach($price_newary as $k=>$v){
            $new_data = $info;
            unset($new_data['id']);
            $new_data['title'] = $good[$k]['title'].'[拆分]';
            $new_data['price'] = $v;
            $new_data['productid'] = $good[$k]['id'];
            //统计利息
            $profits = countprofit($v,$info['daynum'],$info['earnpercent']);
            $new_data['dayaddprice'] = $profits['profitall'];
            $new_data['basicprice']  = $profits['profit_and_day'];
            $z++;
            if($z==1){
                $updata['title'] = $new_data['title'];
                $updata['price'] = $new_data['price'];
                $updata['productid'] = $new_data['productid'];
                $updata['dayaddprice']      = $new_data['dayaddprice'];
                $updata['basicprice']       = $new_data['basicprice'];
                \db(config('db_order_table'))->where("id='".$info['id']."'")->update($updata);
            }else{
                $new_data['buyuidatc']  = 0;
                $new_data['caifen']     = 0;
                \db(config('db_order_table'))->insert($new_data);
            }
        }
        $this->ajaxSuccess("拆分成功");
    }

    /**
     * 取消配对
     */
    public function cancelMatch()
    {
        header("content-type:application/json");
        $order_id = input("id");
        if(empty($order_id)){
            die(json_encode([
                "code"=>1,
                "msg"=>"订单不存在"
            ]));
        }
        //待卖订单
        $original = \db(config('db_order_table'))->where("id", $order_id)->where("peiduistatus", 2)->where("paystatus", "neq", 2)->find();
        if(empty($original)){
            die(json_encode([
                "code"=>1,
                "msg"=>"订单状态不支持取消"
            ]));
        }
        //修改订单状态
        \db(config("db_order_table"))->where("id", $order_id)->update([
            "peiduistatus"=>1,
            "peiduiuid"=>0,
            "peiduitime"=>"",
            "match_pro_id"=>0,
            "match_pro_title"=>"",
            "match_oid"=>0,
            "paystatus"=>0,
            "paytype"=>"",
            "paytime"=>0,
            "payimg"=>""
        ]);

        //已匹配订单
        $match_order = \db(config('db_order_table'))->where("peiduiid", $order_id)->find();
        //删除收益信息
        \db("orderearn")->where("orderid", $match_order["id"])->delete();
        $cancel_order = db(config("db_order_table"))->where("id", $match_order['id'])->find();
        if(!$cancel_order){
            unset($cancel_order['id']);
            db("order_cancel")->insert($cancel_order);
        }
        //删除已匹配订单
        \db(config("db_order_table"))->where("id", $match_order["id"])->delete();
        Message::admin_log(0, "后台取消订单id:" . $order_id);
        die(json_encode([
            "code"=>0,
            "msg"=>"订单取消成功"
        ]));


    }

    //TODO

    /*删除订单*/
    public function remove()
    {
        $orderid = input('id');
        if (empty($orderid)) {
            $this->ajaxError("参数错误！");
        }
        $order = Db::name(config('db_order_table'))
            ->where('id', $orderid)
            ->find();
        if (!$order) {
            $this->ajaxError('无此订单或订单未取消禁止删除');
        }
        /*删除订单*/
        Db::name(config('db_order_table'))
            ->where('id', $orderid)
            ->delete();
        /*删除订单商品*/
        Db::name('order_goods')
            ->where('order_sn', $order["order_sn"])
            ->delete();
        Message::admin_log(0, "后台删除订单id:" . $orderid);
        $this->ajaxSuccess("删除成功！");
    }

    /**
     * 订单导出
     */
    public function order_export()
    {
        $status = input("status");
        if ($status == 'all') {
            $where['or.id'] = ['gt', 0];
        } elseif ($status == 'nopay') {
            $where['or.order_status'] = 0;
        } elseif ($status == 1) {
            $where['or.order_status'] = 1;
        } elseif ($status == 2) {
            $where['or.order_status'] = 2;
        } elseif ($status == 3) {
            $where['or.order_status'] = ["in", [3,5]];
        } elseif ($status == -1) {
            $where['or.order_status'] = 4;
        }
        //搜索条件-用户
        $user_condition = request()->param("user_condition");
        if ($user_condition) {
            $where["us.nick_name|us.mobile|us.id"] = $user_condition;
        }
        //搜索条件-订单
        $or_condition = request()->param("or_condition");
        if ($or_condition) {
            $where["or.id|or.order_sn"] = $or_condition;
        }
        //搜索条件-注册时间
        if (request()->has("time_range")) {
            //解析时间
            $timeRange = request()->param("time_range");
            $timeRange = explode(" ~ ", $timeRange);
            $where['or.create_time'] = ["BETWEEN", [strtotime($timeRange[0] . " 00:00:00"), strtotime($timeRange[1] . " 23:59:59")]];
        }

        //获取订单列表
        $list = Db::name("order")
            ->alias('or')
            ->join('__USER__ us', 'us.id=or.uid', 'LEFT')
            ->where($where)
            ->order("or.id DESC")
            ->field('or.*,us.nick_name as nick_name,us.mobile as mobile')
            ->select();
        foreach ($list as &$item){
            $good_list = \db("order_goods")->where("order_sn", $item["order_sn"])->select();
            $info = "";
            foreach ($good_list as $g){
                $info .= $g["title"]."-".$g["spec_title"]."     ".$g["num"]."     ".$g["price"]."\n";
            }
            $item["good_info"] = $info;
        }
        $header = [
            "订单编号",
            "商品金额",
            "运费",
            "总价",
            "共享豆抵扣",
            "实际支付金额",
            "买家信息",
            "收获信息",
            "商品信息"
        ];
        $body = [];
        foreach ($list as $val){
            $temp = [
                $val["order_sn"],
                $val["goods_price"],
                $val["dispatch_price"],
                $val["total_price"],
                $val["score_fee"],
                $val["money"],
                "昵称：".$val["nick_name"]."\n"."手机号：".$val["mobile"],
                "收货地址：".$val["send_address"]."\n"."联系人姓名：".$val["send_name"]."\n"."联系人电话：".$val["send_mobile"],
                $val["good_info"]
            ];
            $body[] = $temp;
        }
        echo \Excel::export($header, $body);
        exit();
    }
    //查看今日可售订单
    public function cansale(){
      $this->templateTitle("今日可售订单");
      $order = \db(config("db_order_table"))->alias("or")->join("user buy", "or.buyuid=buy.id", "left")->join("user match", "match.id=or.peiduiuid", "left");
      $order2 = \db(config("db_order_table"))->alias("or")->join("user buy", "or.buyuid=buy.id", "left")->join("user match", "match.id=or.peiduiuid", "left");
      $param = input("get.");

      if(isset($param["userinfo"]) && $param["userinfo"] != ""){
          $order->where("buy.username|buy.selfphone", $param["userinfo"]);
          $order2->where("buy.username|buy.selfphone", $param["userinfo"]);
      }
      if(isset($param["title"]) && $param["title"] != ""){
          $order->where("or.title", $param["title"]);
          $order2->where("or.title", $param["title"]);
      }

      if(isset($param["paystatus"]) && $param["paystatus"] != ""){
          $order->where("or.paystatus", $param["paystatus"]);
          $order2->where("or.paystatus", $param["paystatus"]);
      }

      if(isset($param["peiduistatus"]) && $param["peiduistatus"] != ""){
          $order->where("or.peiduistatus", $param["peiduistatus"]);
          $order2->where("or.peiduistatus", $param["peiduistatus"]);
      }
      $now_str_time = date('Ymd');
      $now_int_time = strtotime($now_str_time);
      $order->where('or.cansaletime','<=',$now_int_time);
      $order2->where('or.cansaletime','<=',$now_int_time);

      if(isset($param["zhiding"]) && $param["zhiding"] != ""){
          if($param['zhiding']==1){
              $order->where("or.applyid",'=',0);
              $order2->where("or.applyid",'=',0);
          }
          if($param['zhiding']==2){
              $order->where("or.applyid",'>',0);
              $order2->where("or.applyid",'>',0);
          }

      }

      //拉取所有商品
      $good_id = input("good_id", 0);
      if (!empty($good_id)) {
          $order->where("or.productid", $good_id);
          $order2->where("or.productid", $good_id);
      }
      $this->assign("good_id", $good_id);
      $good_list = db("goods")->field("id, title")->select();
      $this->assign("good_list", $good_list);


      //获取订单列表
      $list = $order->field("or.*, buy.username b_username, buy.selfphone b_selfphone, match.username m_username, match.selfphone m_selfphone")
          ->order("or.id DESC")
          ->paginate(10);
      $this->assign("list", $list);
      $this->assign("param", $param);
      //echo \db(config("db_order_table"))->getlastsql();exit;

      $bar['buyall']  = $order2->sum('basicprice');

      $this->assign("all_money", $bar);
      return $this->fetch('order/cansale');
    }

    /*抢购记录查询*/
    public function qiangorder(){
      $model = db("buylog")->where("id", "gt", 0);



      $datestr = input("datestr");
      if (!empty($datestr) && $datestr != "") {
        $datestr = strtotime($datestr);
        $datestr2= date('Y-m-d',$datestr);
        $datestr = date('Ymd',$datestr);
        $model->where('datestr','=',$datestr);
      }else{
        $datestr2 = date('Y-m-d');
      }
      $this->assign('datestr',$datestr2);




      $good_id = input("good_id", 0);
      if (!empty($good_id)) {
          $model->where("proid", $good_id);
      }
      $this->assign("good_id", $good_id);




      //拉取所有商品
      $good_list = db("goods")->field("id, title,time_start,time_end")->select();
      $this->assign("good_list", $good_list);

      //获取所有用户
      $list = $model->order("id DESC")->paginate(15);
      $page = $list->render();
      $this->assign("list", $list);
      return $this->fetch();
    }

    //改成是否显示是否可售
    function xschange(){
      $id = input("id", 0);
      $data['xs'] = input("xs");

      Message::admin_log(0, "后台设置订单id:" .$id."是否可售");

      $s = db(config('db_order_table'))->where("id='".$id."'")->update($data);
      if($s){
        $this->success('设置成功。');
      }else{
        $this->error('已设置。');
      }
    }

}
